xquery version "1.0";

(: $Id: Tue 19 Jun 2012 01:53:53 PM CEST -- application/xquery $ :)

import module namespace request="http://exist-db.org/xquery/request";
import module namespace session="http://exist-db.org/xquery/session";
import module namespace util="http://exist-db.org/xquery/util";
import module namespace  fn="http://www.w3.org/2005/xpath-functions";

declare option exist:serialize "method=xhtml media-type=text/xml";

(: CONSTANT definitions :)
declare variable $seq_types := ('jms', 'rest', 'rss+atom', 'xmpp', 'email', 'sms');
declare variable $seq_contentTypes := ('Text/xml', 'application/atom+xml', 'application/json', 'text/plain');

(: recuperation des parametres du request :)
declare variable $nodeID := request:get-parameter("nodeID", "");
declare variable $memory := request:get-parameter("memory", "");
declare variable $data_id := request:get-parameter("data_id", "");
declare variable $configID := request:get-parameter("configID", "");

(: recuperation des donnees :)
declare variable $binary := util:binary-doc($data_id);
declare variable $input := util:binary-to-string($binary);
declare variable $input_xml := util:parse($input);

(: declare variable $input_xml := doc($data_id); :)

declare function local:getFireAlert() as element()*
{
	(: trigger fire alert  :)
	if ((fn:number($input_xml//metadata[@attribute="temperature"]) > 60) and (($input_xml//metadata[@attribute="validation"]/text() = 'PreValidated') or ($input_xml//metadata[@attribute="validation"]/text() = 'YES'))) then 
		 (
			<alert>
				<type>{$seq_types[1]}</type>
				<content-type>{$seq_contentTypes[4]}</content-type>
				<destination>{$nodeID}-alerts</destination>
				<msg>Attention!! ***Fire*** !! Temperature value is {$input_xml//metadata[@attribute="temperature"]//text()}. </msg>
			</alert>
			)
	else
		 ()
};

declare function local:getNewDataAlert() as element()*
{
	(
			<alert>
				<type>{$seq_types[1]}</type>
				<content-type>{$seq_contentTypes[1]}</content-type>
				<destination>{$nodeID}-updates</destination>
				<msg>{$input_xml}</msg>
			</alert>
		)
};

declare function local:main() as element()*
{	
(
	<memory>{$data_id}</memory>,
	<alerts>
		{local:getFireAlert()}
		{local:getNewDataAlert()}
	</alerts>
)
};


<GeneratedAlerts>
	{local:main()}
</GeneratedAlerts>
